# encoding:utf-8
# from websocket import create_connection
# ws = create_connection("ws://127.0.0.1:7010")
# ws.send("Hello, World")##发送消息
# result = ws.recv()##接收消息
# ws.close()

#模拟停车场，中间件往停车场用webSocket接口发送数据，停车场接收之后返回websocket响应。停车场主动上报的是用rest接口，websocket接收到的还用websocket回过去
import websocket

try:
    import thread
except ImportError:
    import _thread as thread
import time
from _thread import start_new_thread
import ssl
from threading import Condition


class WebSocketClient:
    def __init__(self,url,ui):
        self.url = url
        self.ui = ui
        self.isRunning = False
        self.shouldReconnect = False
        self.ws = None
        self.device=None
        self.cond = Condition()
        self.delay = 5
        self.connect()


    def connect(self):
        websocket.enableTrace(False) #禁止跟踪
        try:
            self.ws = websocket.WebSocketApp(self.url,
                                             on_message=self.on_message,
                                             on_error=self.on_error,
                                             on_close=self.on_close,
                                             on_open=self.on_open)

            start_new_thread(self.ws.run_forever, (None,))
            self.cond.acquire()
            if not self.isRunning:
                self.cond.wait()
            self.shouldReconnect = False
            self.cond.release()
        except:
            self.shouldReconnect = True
            import traceback
            traceback.print_exc()


    def disconnect(self):
        self.ws.close()
        self.ui.emit(self.ui.LOGPRINT, '对讲socket关闭：' + "### disconnect ##")


    def on_message(self,message):
        print(message)
        if 'HD' in message:
            self.cond.acquire()
            self.device = message.split(',')[-1]
            self.cond.notify()
            self.cond.release()
            print('设备名：'+self.device)

    def on_open(self):
        print("### opened! ###")
        self.cond.acquire()
        self.isRunning = True
        self.cond.notify()
        self.cond.release()

    def on_error(self,error):
        self.ui.emit(self.ui.LOGPRINT, "错误" + "on_error error!"+error)
        self.shouldReconnect = True

    def on_close(self):
        print('####closed####')
        self.ui.emit(self.ui.LOGPRINT,'对讲socket关闭：'+"### closed ##")
        #如果对讲终端没有开启，会由于wait而阻塞
        self.cond.acquire()
        self.isRunning=False
        self.cond.notify()
        self.cond.release()
        self. shouldReconnect = True

    def sendCmd(self,cmdName):
        try :
            self.ws.send(cmdName)
        except:
            import traceback
            traceback.print_exc()

    def fetchDevice(self):
        try:
            self.ws.send("devices")
        except:
            import traceback
            traceback.print_exc()#

    def startTalk(self):
        try:
            self.fetchDevice()
            self.cond.acquire()
            if not self.device:
                self.cond.wait()
            self.cond.release()
            self.sendCmd(self.device)
            self.ui.emit(self.ui.LOGPRINT, '开始对讲')
        except:
            import traceback
            traceback.print_exc()

    def stopTalk(self):
        try:
            self.sendCmd("stop")
            self.ui.emit(self.ui.LOGPRINT, '结束对讲')
        except:
            import traceback
            traceback.print_exc()


    def copyMC(self):
        while self.isRunning:
            if self.shouldReconnect:
                self.connect()
            self.startTalk()
            self.waitIfRunning(10)
            self.stopTalk()
            self.waitIfRunning(60)
   #     self.stopTalk()
        self.disconnect()

    def waitIfRunning(self,interval):
        t = 0
        while t < interval:
            if self.isRunning:
                time.sleep(1)
                t += 1
            else:
                break

    def shutdown(self):
        self.stopTalk()
        self.disconnect()


if __name__ == '__main__':
    url = "ws://127.0.0.1:9006/JavaWebSocket/websocket"
    print ("********************")
    wb = WebSocketClient(url)
    #time.sleep(5)
    # wb.fetchDevice()
    time.sleep(1)
    wb.startTalk(wb.fetchDevice())
    time.sleep(5)
    wb.stopTalk()
    time.sleep(1)
    wb.disconnect()
    print('end')




